package pl.wroc.uni.ii.puzzle.activity;

import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.restlet.data.MediaType;
import org.restlet.resource.ClientResource;

import pl.wroc.uni.ii.puzzle.R;
import pl.wroc.uni.ii.puzzle.data.DatabaseAdapter;
import pl.wroc.uni.ii.puzzle.data.DateDeserializer;
import pl.wroc.uni.ii.puzzle.data.Score;
import android.app.Activity;
import android.database.SQLException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class HighScoresActivity extends Activity {

	private static final String PUZZLE_WS_ADDRESS = "http://puzzle-scores.appspot.com/scores/123";
	private ListView globalHighScoreListView;
	private ListView myHighScoreListView;
	
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);	
		setContentView(R.layout.high_score);
		initTabsLayout();
		new HighScoresLookupTask().execute();
	}

	private void initTabsLayout() {        
        myHighScoreListView =(ListView)findViewById(R.id.myHighScoreListView);
        globalHighScoreListView =(ListView)findViewById(R.id.globalHighScoreListView);
        String[] loadingStrings = new String[]{"Loading..."};
        fillListViewWithStrings(myHighScoreListView, loadingStrings);
        fillListViewWithStrings(globalHighScoreListView, loadingStrings);
 
        TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
        tabHost.setup();
        tabHost.addTab(tabHost.newTabSpec("myHighScores")
        		.setIndicator("My High Scores",getResources().getDrawable(R.drawable.star))
        		.setContent(R.id.myHighScoreListView));
        tabHost.addTab(tabHost.newTabSpec("globalHighScores")
        		.setIndicator("Global High Scores",getResources().getDrawable(R.drawable.cup))
        		.setContent(R.id.globalHighScoreListView));
        tabHost.setCurrentTab(0);	
	}
	
	private void fillTabWithMyHighScoreList(List<Score> highScoreList) {
		fillListViewWithScoreList(myHighScoreListView, highScoreList);
	}

	private void fillTabWithGlobalHighScoreList(List<Score> highScoreList) {
		fillListViewWithScoreList(globalHighScoreListView, highScoreList);
	}
	
	private void fillListViewWithScoreList(ListView listView, List<Score> scoreList) {
		if (scoreList != null) {			
			String[] scoreStrings = new String[scoreList.size()];
			int i = 0;
			for (Score hs : scoreList) {
				scoreStrings[i] = hs.toString();
				i++;
			}
			fillListViewWithStrings(listView, scoreStrings);
		}
	}
	
	private void fillListViewWithStrings(ListView listView, String[] strings) {
		ArrayAdapter<String> aa = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , strings);
		listView.setAdapter(aa);
		listView.refreshDrawableState();
	}

	private List<Score> retrieveMyHighScore() {
		DatabaseAdapter databaseAdapter = new DatabaseAdapter(this);
		try {
			databaseAdapter.open();
			List<Score> myHighScores = databaseAdapter.getHighScores();
			databaseAdapter.close();
			return myHighScores;
		} catch (SQLException e) {
			Log.e(HighScoresActivity.class.getName(), "can't receive data from base", e);
		}
		return null;
	}
	
	private List<Score> retrieveGlobalHighScore() {
		ClientResource cr = new ClientResource(PUZZLE_WS_ADDRESS);
		GsonBuilder gsonb = new GsonBuilder();
		gsonb.registerTypeAdapter(Date.class, new DateDeserializer());
		Gson gson = gsonb.create();
		try {
			String scoreString = cr.get(MediaType.APPLICATION_JSON).getText();
			Score score = gson.fromJson(scoreString, Score.class);
			List<Score> scores = new LinkedList<Score>();
			scores.add(score);
			return scores;
		} catch (IOException e) {
			Log.e(HighScoresActivity.class.getName(), "can't receive data from server", e);
		}
		return null;
	}
	
	private class HighScoresLookupTask extends AsyncTask <Void, List<Score>, List<Score>> {
		
		@SuppressWarnings("unchecked")
		@Override
		protected List<Score> doInBackground(Void... params) {
			List<Score> scores = retrieveMyHighScore();
			publishProgress(scores);
			return retrieveGlobalHighScore();
		}
		
		@Override
		protected void onProgressUpdate(List<Score>... scores) {
			super.onProgressUpdate(scores);
			fillTabWithMyHighScoreList(scores[0]);
		}

		@Override
		protected void onPostExecute(List<Score> scores) {
			super.onPostExecute(scores);
			fillTabWithGlobalHighScoreList(scores);
		}
	}
	
}
